<template>
    <div class="exams">
      <div class="page-header">
        <h1>考试管理</h1>
        <el-button type="primary" @click="showCreateDialog = true">
          <el-icon><Plus /></el-icon>
          创建考试
        </el-button>
      </div>

      <!-- 搜索和筛选 -->
      <div class="filters">
        <el-input
          v-model="searchQuery"
          placeholder="搜索考试名称或描述"
          style="width: 300px; margin-right: 10px;"
          @input="handleSearch"
        />
        <el-select v-model="statusFilter" placeholder="状态筛选" style="width: 150px; margin-right: 10px;" @change="handleSearch">
          <el-option label="全部" value="" />
          <el-option label="草稿" value="draft" />
          <el-option label="已发布" value="published" />
          <el-option label="进行中" value="ongoing" />
          <el-option label="已完成" value="completed" />
        </el-select>
        <el-select v-model="typeFilter" placeholder="类型筛选" style="width: 150px;" @change="handleSearch">
          <el-option label="全部" value="" />
          <el-option label="正式考试" value="formal" />
          <el-option label="练习考试" value="practice" />
        </el-select>
      </div>

      <!-- 考试列表 -->
      <el-table :data="exams" style="width: 100%" v-loading="loading">
        <el-table-column prop="title" label="考试名称" />
        <el-table-column prop="description" label="描述" show-overflow-tooltip />
        <el-table-column prop="start_time" label="开始时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.start_time) }}
          </template>
        </el-table-column>
        <el-table-column prop="end_time" label="结束时间" width="180">
          <template #default="{ row }">
            {{ formatDateTime(row.end_time) }}
          </template>
        </el-table-column>
        <el-table-column prop="duration" label="时长" width="100">
          <template #default="{ row }">
            {{ row.duration }} 分钟
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusType(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="question_count" label="题目数量" width="100" />
        <el-table-column label="操作" width="280">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="$router.push(`/exam/${row.id}`)">
              详情
            </el-button>
            <el-button type="success" size="small" @click="$router.push(`/questions?exam_id=${row.id}`)">
              题目
            </el-button>
            <el-button type="warning" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>

      <!-- 创建考试对话框 -->
      <el-dialog
        v-model="showCreateDialog"
        title="创建考试"
        width="600px"
        :before-close="handleDialogClose"
      >
        <el-form
          ref="examFormRef"
          :model="examForm"
          :rules="examRules"
          label-width="100px"
        >
          <el-form-item label="考试名称" prop="title">
            <el-input v-model="examForm.title" placeholder="请输入考试名称" />
          </el-form-item>
          <el-form-item label="考试描述" prop="description">
            <el-input
              v-model="examForm.description"
              type="textarea"
              :rows="3"
              placeholder="请输入考试描述"
            />
          </el-form-item>
          <el-form-item label="考试类型" prop="exam_type">
            <el-select v-model="examForm.exam_type" placeholder="请选择考试类型">
              <el-option label="正式考试" value="formal" />
              <el-option label="练习考试" value="practice" />
            </el-select>
          </el-form-item>
          <el-form-item label="开始时间" prop="start_time">
            <el-date-picker
              v-model="examForm.start_time"
              type="datetime"
              placeholder="选择开始时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="结束时间" prop="end_time">
            <el-date-picker
              v-model="examForm.end_time"
              type="datetime"
              placeholder="选择结束时间"
              format="YYYY-MM-DD HH:mm:ss"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
          <el-form-item label="考试时长" prop="duration">
            <el-input-number
              v-model="examForm.duration"
              :min="1"
              :max="480"
              placeholder="请输入考试时长（分钟）"
            />
          </el-form-item>
          <el-form-item label="总分" prop="total_score">
            <el-input-number
              v-model="examForm.total_score"
              :min="1"
              :max="1000"
              placeholder="请输入总分"
            />
          </el-form-item>
          <el-form-item label="及格分" prop="pass_score">
            <el-input-number
              v-model="examForm.pass_score"
              :min="1"
              :max="1000"
              placeholder="请输入及格分数"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="showCreateDialog = false">取消</el-button>
            <el-button type="primary" @click="handleCreate" :loading="creating">
              创建
            </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup>
  import { ref, reactive, onMounted } from 'vue';
  import api from '../api';
  import { ElMessage, ElMessageBox } from 'element-plus';
  import { Plus } from '@element-plus/icons-vue';
  
  const exams = ref([]);
  const loading = ref(false);
  const creating = ref(false);
  const showCreateDialog = ref(false);
  const examFormRef = ref();
  
  // 分页和筛选
  const currentPage = ref(1);
  const pageSize = ref(10);
  const total = ref(0);
  const searchQuery = ref('');
  const statusFilter = ref('');
  const typeFilter = ref('');
  
  // 考试表单
  const examForm = reactive({
    title: '',
    description: '',
    exam_type: 'formal',
    start_time: '',
    end_time: '',
    duration: 60,
    total_score: 100,
    pass_score: 60
  });
  
  // 表单验证规则
  const examRules = {
    title: [
      { required: true, message: '请输入考试名称', trigger: 'blur' },
      { min: 2, max: 100, message: '考试名称长度在 2 到 100 个字符', trigger: 'blur' }
    ],
    description: [
      { required: true, message: '请输入考试描述', trigger: 'blur' },
      { max: 500, message: '考试描述不能超过 500 个字符', trigger: 'blur' }
    ],
    exam_type: [
      { required: true, message: '请选择考试类型', trigger: 'change' }
    ],
    start_time: [
      { required: true, message: '请选择开始时间', trigger: 'change' }
    ],
    end_time: [
      { required: true, message: '请选择结束时间', trigger: 'change' }
    ],
    duration: [
      { required: true, message: '请输入考试时长', trigger: 'blur' }
    ],
    total_score: [
      { required: true, message: '请输入总分', trigger: 'blur' }
    ],
    pass_score: [
      { required: true, message: '请输入及格分数', trigger: 'blur' }
    ]
  };
  
  const formatDateTime = (datetime) => {
    return new Date(datetime).toLocaleString('zh-CN');
  };
  
  const getStatusType = (status) => {
    const statusMap = {
      'draft': 'info',
      'published': 'success',
      'ongoing': 'warning',
      'completed': 'danger'
    };
    return statusMap[status] || 'info';
  };
  
  const getStatusText = (status) => {
    const statusMap = {
      'draft': '草稿',
      'published': '已发布',
      'ongoing': '进行中',
      'completed': '已完成'
    };
    return statusMap[status] || '未知';
  };
  
  const loadExams = async () => {
    loading.value = true;
    try {
      const params = {};
      
      // 只添加非空的参数
      if (searchQuery.value) {
        params.search = searchQuery.value;
      }
      if (statusFilter.value) {
        params.status = statusFilter.value;
      }
      if (typeFilter.value) {
        params.exam_type = typeFilter.value;
      }
      
      // 分页参数
      params.skip = (currentPage.value - 1) * pageSize.value;
      params.limit = pageSize.value;
      
      const response = await api.exams.getExams(params);
      exams.value = response.data.items || response.data;
      total.value = response.data.total || (response.data.items ? response.data.items.length : 0);
    } catch (error) {
      console.error('加载考试列表失败:', error);
      ElMessage.error('加载考试列表失败');
    } finally {
      loading.value = false;
    }
  };
  
  const handleSearch = () => {
    currentPage.value = 1;
    loadExams();
  };
  
  const handleSizeChange = (size) => {
    pageSize.value = size;
    loadExams();
  };
  
  const handleCurrentChange = (page) => {
    currentPage.value = page;
    loadExams();
  };
  
  const handleCreate = async () => {
    if (!examFormRef.value) return;
    
    await examFormRef.value.validate(async (valid, fields) => {
      if (valid) {
        creating.value = true;
        try {
          const response = await api.exams.createExam(examForm);
          ElMessage.success('考试创建成功');
          showCreateDialog.value = false;
          resetForm();
          loadExams();
        } catch (error) {
          ElMessage.error('创建考试失败');
        } finally {
          creating.value = false;
        }
      }
    });
  };
  
  const handleEdit = (exam) => {
    ElMessage.info('编辑功能开发中...');
  };
  
  const handleDelete = async (exam) => {
    try {
      await ElMessageBox.confirm(
        `确定要删除考试"${exam.title}"吗？此操作不可恢复。`,
        '删除确认',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
      );
      
      await api.exams.deleteExam(exam.id);
      ElMessage.success('考试删除成功');
      loadExams();
    } catch (error) {
      if (error !== 'cancel') {
        ElMessage.error('删除考试失败');
      }
    }
  };
  
  const handleDialogClose = () => {
    showCreateDialog.value = false;
    resetForm();
  };
  
  const resetForm = () => {
    if (examFormRef.value) {
      examFormRef.value.resetFields();
    }
    Object.assign(examForm, {
      title: '',
      description: '',
      exam_type: 'formal',
      start_time: '',
      end_time: '',
      duration: 60,
      total_score: 100,
      pass_score: 60
    });
  };
  
  onMounted(() => {
    loadExams();
  });
  </script>
  
  <style scoped>
.exams {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.page-header h1 {
  margin: 0;
  font-size: 24px;
  color: #303133;
}

.filters {
  display: flex;
  gap: 10px;
  margin-bottom: 20px;
}

.pagination {
  display: flex;
  justify-content: center;
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
</style>